package cn.itcast.scala.course04

/**
  * 伴生类和伴生对象
  * create by zhangtian on 2018/12/29
  */
object ApplyApp {
  def main(args: Array[String]): Unit = {
    /*for(i <- 1 to 10) {
      ApplyTest.incr // 单例，获取的临时值不被清空
    }

    println("count: " +ApplyTest.count) // 说明object本身就是一个单例对象*/

    println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`")
    val b = ApplyTest() // 调用的是object的apply  ==>object apply

    val c = new ApplyTest()
    println(c)
    println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
    c()

    // 类名()  ==> Object.apply
    // 对象()  ==> Class.apply
  }
}

/**
  * 伴生类和伴生对象
  * 如果有一个class还有一个与class对应的object
  * 那么就称这个object是class的伴生对象，class是object的伴生类
  */
class ApplyTest {
  println("class ApplyTest enter ...... ")

  def apply() = {
    println("class ApplyTest apply ...... ")
  }

  println("class ApplyTest enter ...... ")
}

// 单例
object ApplyTest {
  println("object ApplyTest enter ...... ")

  var count = 0

  def incr = {
    count += 1
  }

  // 最佳实践，在Object的apply方法中去new Class
  def apply() = {
    println("object ApplyTest apply ...... ")
    new ApplyTest // 在object的apply中new class
  }

  println("object ApplyTest leave ...... ")
}
